// 地图应用主类
class MapApplication {
    constructor() {
        this.mapManager = null;
        this.currentSearchType = 'all';
        this.searchDebounceTimer = null;
        
        // 等待DOM加载完成后初始化
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.init());
        } else {
            this.init();
        }
    }

    // 初始化应用
    async init() {
        try {
            console.log('Initializing map application...');
            
            // 确保地图容器存在
            const mapContainer = document.getElementById('map-container');
            if (!mapContainer) {
                throw new Error('Map container not found');
            }

            // 初始化地图管理器
            this.mapManager = new MapManager('map-container', {
                zoom: 12,
                center: [117.227239, 31.820587],
                viewMode: '3D',
                mapStyle: 'amap://styles/normal'
            });

            // 绑定事件处理器
            this.bindEventHandlers();
            
            // 加载初始数据
            await this.loadInitialData();

            console.log('Map application initialized successfully');
        } catch (error) {
            console.error('Failed to initialize map application:', error);
            this.showError('地图初始化失败，请刷新页面重试');
        }
    }

    // 绑定事件处理器
    bindEventHandlers() {
        // 工具按钮事件
        document.getElementById('drawPointBtn')?.addEventListener('click', () => this.handleToolClick('marker'));
        document.getElementById('drawLineBtn')?.addEventListener('click', () => this.handleToolClick('polyline'));
        document.getElementById('drawPolygonBtn')?.addEventListener('click', () => this.handleToolClick('polygon'));
        document.getElementById('measureDistanceBtn')?.addEventListener('click', () => this.handleToolClick('rule'));
        document.getElementById('measureAreaBtn')?.addEventListener('click', () => this.handleToolClick('measureArea'));
        document.getElementById('clearBtn')?.addEventListener('click', () => this.handleClear());

        // 图层控制事件
        document.getElementById('satelliteBtn')?.addEventListener('click', () => this.toggleLayer('satellite'));
        document.getElementById('trafficBtn')?.addEventListener('click', () => this.toggleLayer('traffic'));
        document.getElementById('toggle3DBtn')?.addEventListener('click', () => this.toggle3DMode());

        // 搜索相关事件
        const searchInput = document.getElementById('tipinput');
        if (searchInput) {
            searchInput.addEventListener('input', (e) => this.handleSearch(e.target.value));
            searchInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    this.handleSearch(e.target.value, true);
                }
            });
        }

        // 搜索过滤器事件
        document.querySelectorAll('.filter-button')?.forEach(button => {
            button.addEventListener('click', () => this.handleFilterChange(button.dataset.type));
        });

        // 移动端菜单事件
        const mobileMenuButton = document.getElementById('mobileMenuButton');
        const mobileMenu = document.getElementById('mobileMenu');
        if (mobileMenuButton && mobileMenu) {
            mobileMenuButton.addEventListener('click', () => {
                mobileMenu.classList.toggle('hidden');
            });
        }
    }

    // 加载初始数据
    async loadInitialData() {
        try {
            // 添加合肥市边界
            await this.mapManager.addDistrictBoundary('合肥市');

            // 加载默认地点
            const response = await PlacesAPI.getAllPlaces();
            if (response.status === 'success') {
                this.addPlacesToMap(response.data);
            }
        } catch (error) {
            console.error('加载初始数据失败:', error);
            this.showError('加载数据失败，请刷新页面重试');
        }
    }

    // 处理工具点击
    handleToolClick(toolType) {
        this.resetToolButtons();
        const button = document.querySelector(`[data-tool="${toolType}"]`);
        if (button) {
            button.classList.add('active');
        }
        this.mapManager.startDraw(toolType);
    }

    // 重置工具按钮状态
    resetToolButtons() {
        document.querySelectorAll('.tool-button').forEach(btn => {
            btn.classList.remove('active');
        });
    }

    // 切换图层
    toggleLayer(layerName) {
        const button = document.getElementById(`${layerName}Btn`);
        const isActive = this.mapManager.toggleLayer(layerName);
        if (button) {
            button.classList.toggle('active', isActive);
        }
    }

    // 切换3D模式
    toggle3DMode() {
        const button = document.getElementById('toggle3DBtn');
        const is3D = button.classList.toggle('active');
        this.mapManager.setViewMode(is3D);
    }

    // 处理搜索
    handleSearch(keyword, immediate = false) {
        if (this.searchDebounceTimer) {
            clearTimeout(this.searchDebounceTimer);
        }

        if (immediate) {
            this.performSearch(keyword);
        } else {
            this.searchDebounceTimer = setTimeout(() => {
                this.performSearch(keyword);
            }, 300);
        }
    }

    // 执行搜索
    async performSearch(keyword) {
        if (!keyword) {
            this.clearSearchResults();
            return;
        }

        try {
            const response = await PlacesAPI.searchPlaces(keyword, {
                type: this.currentSearchType
            });

            if (response.status === 'success') {
                this.displaySearchResults(response.data);
            } else {
                this.showError('搜索失败，请重试');
            }
        } catch (error) {
            console.error('搜索错误:', error);
            this.showError('搜索出错，请稍后重试');
        }
    }

    // 显示搜索结果
    displaySearchResults(results) {
        const panel = document.getElementById('panel');
        if (!panel) return;

        if (results.length === 0) {
            panel.innerHTML = '<div class="p-4">未找到相关地点</div>';
            return;
        }

        // 清除地图上现有的标记
        this.mapManager.clear();

        // 显示搜索结果
        panel.innerHTML = `
            <div class="p-4">
                <h2 class="text-lg font-semibold mb-4">搜索结果 (${results.length})</h2>
                <div class="space-y-4">
                    ${results.map(place => this.createPlaceCard(place)).join('')}
                </div>
            </div>
        `;

        // 在地图上添加标记
        this.addPlacesToMap(results);

        // 调整地图视野
        this.mapManager.map.setFitView();
    }

    // 创建地点卡片HTML
    createPlaceCard(place) {
        return `
            <div class="place-card fade-in">
                <h3 class="text-lg font-semibold">${place.name}</h3>
                <p class="text-gray-600">${place.description || '暂无描述'}</p>
                <div class="mt-2">
                    ${place.category ? `<span class="tag">${place.category}</span>` : ''}
                    ${place.attributes?.map(attr => 
                        `<span class="tag">${attr.name}: ${attr.value}</span>`
                    ).join('') || ''}
                </div>
            </div>
        `;
    }

    // 在地图上添加地点标记
    addPlacesToMap(places) {
        places.forEach(place => {
            if (place.latitude && place.longitude) {
                const marker = new AMap.Marker({
                    position: [place.longitude, place.latitude],
                    title: place.name,
                    animation: 'AMAP_ANIMATION_DROP'
                });

                const infoWindow = new AMap.InfoWindow({
                    content: `
                        <div class="info-window">
                            <h3>${place.name}</h3>
                            <p>${place.description || '暂无描述'}</p>
                            ${place.attributes ? `
                                <div class="mt-2">
                                    ${place.attributes.map(attr => 
                                        `<p>${attr.name}: ${attr.value}</p>`
                                    ).join('')}
                                </div>
                            ` : ''}
                        </div>
                    `,
                    offset: new AMap.Pixel(0, -30)
                });

                marker.on('click', () => {
                    infoWindow.open(this.mapManager.map, marker.getPosition());
                });

                this.mapManager.map.add(marker);
            }
        });
    }

    // 处理过滤器变更
    handleFilterChange(type) {
        document.querySelectorAll('.filter-button').forEach(btn => {
            btn.classList.toggle('active', btn.dataset.type === type);
        });
        this.currentSearchType = type;

        const searchInput = document.getElementById('tipinput');
        if (searchInput && searchInput.value) {
            this.handleSearch(searchInput.value, true);
        }
    }

    // 清除搜索结果
    clearSearchResults() {
        const panel = document.getElementById('panel');
        if (panel) {
            panel.innerHTML = '';
        }
        this.mapManager.clear();
    }

    // 处理清除操作
    handleClear() {
        this.mapManager.clear();
        this.clearSearchResults();
        this.resetToolButtons();
    }

    // 显示错误信息
    showError(message) {
        // 可以使用更好的提示组件替换
        alert(message);
    }
}

// 创建应用实例
window.app = new MapApplication(); 